package com.linln.admin.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.linln.admin.pcs.service.RsaService;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.ObjectUtils;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author liudong
 * @date 2025/3/26 16:17
 */
public class ToolUtils {
    private final static Logger logger = LoggerFactory.getLogger(ToolUtils.class);
    // 测试环境配置
    private static final String IV_STRING = "zEXaPrpd67fPrkMr";
    public static String aesEncrypt(String content, String key) throws Exception {
        byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec skeySpec = new SecretKeySpec(keyBytes, "AES");

        byte[] ivBytes = IV_STRING.getBytes(StandardCharsets.UTF_8);
        IvParameterSpec iv = new IvParameterSpec(ivBytes);

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

        byte[] encrypted = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
        return bytesToHex(encrypted);
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    public static String generateMD5Signature(Map<String, String> params) throws Exception {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        if (sb.length() > 0) sb.deleteCharAt(sb.length() - 1);

        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] digest = md.digest(sb.toString().getBytes(StandardCharsets.UTF_8));
        return bytesToHex(digest);
    }

    public static String buildFinalUrl(String API_URL,String APP_ID,long ts, String sign) {
        return API_URL + "?appId=" + APP_ID + "&ts=" + ts + "&sign=" + sign;
    }

    public static String sendPostRequest(String url, String body) throws Exception {
        HttpRequest postHttpReq = HttpUtil.createPost(url);

        // 加入请求参数，转换成JSON后的
        postHttpReq.body(body);
        // 发起请求
        HttpResponse response = postHttpReq.execute();
        String body1 = response.body();

        // 返回结果body
        return body1;
    }

    private static JSONArray parseResponse(String response) {
        JSONObject jsonObject = JSONObject.parseObject(response);
        if (ObjectUtils.isNotEmpty(jsonObject)){
            boolean ss = jsonObject.getBoolean("success");
            logger.error("根据身份证获取患者档案信息参数success:"+ss);
            if (ss){
                JSONArray data = jsonObject.getJSONArray("data");
                return data;
            }
        }
        return null;
    }
}
